package jude.java.money.task;

import java.util.List;

import jude.java.framework.thread.Stoppable;
import jude.java.money.provide.Provider;
import jude.java.money.provide.SimpleProvider;

public abstract class BaseTask<T> implements Runnable, Stoppable {
	
	protected Provider<T> provider;
	private boolean finished;
	private boolean stopped;
	private TaskDetails detail;
	
	public BaseTask(Provider<T> provider) {
		this.provider = provider;
		detail = new TaskDetails();
	}

	public BaseTask(List<T> objs) {
		this(new SimpleProvider<T>(objs));
	}
	
	public BaseTask(T... objs) {
		this(new SimpleProvider<T>(objs));
	}
	
	@Override
	public void run() {
		detail.reset();
		TaskContext.set(detail);
		T o;
		while (!stopped && (o = provider.get()) != null) {
			if (beforeExecute(o)) {
				execute(o);
			}
			afterExecute(o);
		}
		finished = true;
	}
	
	/**
	 * @return true to execute the obj
	 * */
	protected boolean beforeExecute(T o) {
		return true;
	}

	protected abstract void execute(T obj);
	
	protected boolean afterExecute(T o) {
		return true;
	}
	
	public boolean isFinished() {
		return finished;
	}
	
	/**
	 * 尝试放弃当前的任务, 执行下一个
	 */
	public void abandon() {
		
	}
	
	@Override
	public void stop() {
		stopped = true;
	}
	
//	public TaskDetails getDetails() {
//		return details;
//	}
	
	public String getTaskDetails() {
		return detail.toString();
	}
	
	public long getTimeout() {
		return System.currentTimeMillis() - detail.getLastActiveTime();
	}
}
